import { defineEventHandler, getHeaders, readBody } from 'h3'
import { query, execute } from '../utils/db'
import dayjs from 'dayjs'
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'

function generateId() {
  const timestamp = Date.now().toString(36)
  return `${timestamp}`
}

export default defineEventHandler(async (event) => {
  console.log('请求头:', getHeaders(event))
  const body = await readBody(event)
  console.log('请求体:', JSON.stringify(body, null, 2))
  const method = event.node.req.method

  if (method === 'POST') {
    try {
      const { username, password, role_id = 2, disable = 0 } = body
      const create_time = dayjs().format('YYYY-MM-DD HH:mm:ss')

      // 参数验证
      if (!username?.trim()) {
        return sendErrorResponse(event, 400, '用户名不能为空')
      }

      if (!password || password.length < 6) {
        return sendErrorResponse(event, 400, '密码至少需要6位')
      }

      // 检查用户名是否存在
      const { results } = await query(
        'SELECT 1 FROM user WHERE username = ? LIMIT 1',
        [username.trim()]
      )

      if (results.length > 0) {
        return sendErrorResponse(event, 409, '用户名已被注册')
      }

      // 生成用户ID
      const userId = generateId()

      // 执行插入（确保占位符和参数数量匹配）
      await execute(
        `INSERT INTO user 
       (username, password, role_id, user_id, create_time, disable)
       VALUES (?, ?, ?, ?, ?, ?)`,  // 6个占位符
        [
          username.trim(),
          password,
          role_id,
          userId,
          create_time,
          disable
        ]  // 6个参数
      )

      // 返回创建的用户数据
      const { results: [user] } = await query(
        'SELECT user_id, username, role_id, disable, create_time FROM user WHERE user_id = ?',
        [userId]
      )

      return sendSuccessResponse(event, user)

    } catch (error: any) {
      console.error('注册错误:', error)

      let message = '注册失败'
      if (error.message.includes('syntax')) {
        message = '数据库语句错误'
      } else if (error.message.includes('Unknown column')) {
        message = '数据库字段不存在'
      }

      return sendErrorResponse(
        event,
        500,
        message,
        { error: error.message }
      )
    }
  }

})